import datetime
import time

from django.contrib.auth import logout
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseRedirect
from django.http import JsonResponse
from django.shortcuts import render

from .models import Employee
from .models import Floor
from .models import MeetingEmp
from .models import Room
from .models import Department
from .models import roomBooking as RoomBooking


# Create your views here.
def loginView(request):
    context={}
    return render(request, 'login.html', context)

def login(request):
    context = {}
    if request.method == 'GET':
        return render(request,'login.html',context)
    else:
        name=request.POST['name']
        pswd=request.POST['password']
        try:
            p=Employee.objects.get(name=name,password=pswd)
        except ObjectDoesNotExist:
            print("用户名或密码错误")
            return HttpResponseRedirect('/login/')
        print(str(Employee.objects.get(name=name,password=pswd)))
        request.session['userId']=p.id
        request.session['username']=p.name
        request.session['pswd']=p.password
        request.session['permissions']=p.permissions
        request.session['user']=p
        # return HttpResponse(str(Employee.objects.get(name=name,password=pswd)))
        return  HttpResponseRedirect('/index/')
def myLogout(request):
    logout(request)
    request.session.flush()
    return  HttpResponseRedirect('/login/')
def index(request):
    context={}
    employees=list(Employee.objects.all())
    departments=list(Department.objects.all())
    floors = list(Floor.objects.all())
    strtime=time.strftime('%Y-%m-%d',time.localtime(time.time()))
    floornum=8
    if request.method=="POST":
        strtime=request.POST['roomDate']
        floornum=int(request.POST['floornum'])
    if len(floors) > 0:
        rooms = list(Room.objects.filter(floor=floornum, state=True))
        answers = list()
        for room in rooms:
            dates = datetime.datetime.strptime(strtime, '%Y-%m-%d').date()
            bookrooms = list(RoomBooking.objects.filter(roomId=room, bookDate=dates))
            orderTime = [0] * 26
            answer = {}
            for bookroom in bookrooms:
                count = bookroom.end - 1
                while count >= 0:
                    count -= 1
                    orderTime[count + bookroom.start] = 1
            answer['room'] = room
            answer['orderTime'] = orderTime
            answers.append(answer)
        context['answers'] = answers
    context['employees'] = employees
    context['departments'] = departments
    context['floors'] = floors
    context['date']=strtime
    context['floornum']=floornum
    print(request.session.get('userId', default=0), request.session.get('username'))
    if request.session.get('bookAnswer') is not None and request.session.get('bookAnswer') is False:
        context['bookAnswer']=False
        context['message']="预订失败"
    return render(request,'index.html',context)

def roomManage(request):
    context={}
    floors = list(Floor.objects.all())
    if len(floors)>0:
        rooms=list(Room.objects.filter(floor=floors[0].floorNum))
        context['rooms'] = rooms
    context['floors'] = floors
    return render(request,'roomManage.html',context)

def deleteRoom(request):
    context={}
    roomId=request.POST['roomId']
    room=Room.objects.filter(id=int(roomId))
    room.delete()
    return JsonResponse(context)

def addRoom(request):
    room=Room()
    room.floorNum=int(request.POST['floor'])
    room.name=request.POST['name']
    room.maxFill=int(request.POST['maxFill'])
    room.permissions=request.POST['permissions']
    data="true"
    if request.POST.get('hasTv') is not None:
        room.hasTv = data == request.POST['hasTv']
    if request.POST.get('hasTel') is not None:
        room.hasTv = data == request.POST['hasTel']
    if request.POST.get('hasMv') is not None:
        room.hasTv = data == request.POST['hasMv']

    room.state=data==request.POST['state']
    room.save()
    return HttpResponseRedirect('/roomManage/')

def editRoom(request):
    room=Room.objects.get(id=int(request.POST['roomId']))
    room.floorNum = int(request.POST['floor'])
    room.name = request.POST['name']
    room.maxFill = int(request.POST['maxFill'])
    room.permissions = request.POST['permissions']
    data = "true"
    if request.POST.get('hasTv') is not None:
        room.hasTv = data == request.POST['hasTv']
    if request.POST.get('hasTel') is not None:
        room.hasTel = data == request.POST['hasTel']
    if request.POST.get('hasMv') is not None:
        room.hasMv = data == request.POST['hasMv']
    room.state = data == request.POST['state']
    room.save()
    return HttpResponseRedirect('/roomManage/')
def getRoom(request):
    #json序列化的问题
    roomId=int(request.GET["roomId"])
    room=list(Room.objects.filter(id=roomId))[0]
    context={}
    context["state"]=room.state
    context["id"]=room.id
    context["permissions"]=room.permissions
    context["name"]=room.name
    context["maxFill"]=room.maxFill
    context["floor"]=room.floor
    context["hasTv"]=room.hasTv
    context['hasMv']=room.hasMv
    context['hasTel']=room.hasTel
    return JsonResponse(context,safe=False)
def ajax_list(request):
    a={}
    a['name']='gqb'
    a['wife']='dyq'
    return JsonResponse(a, safe=False)


def bookRoom(request):
    room=Room.objects.get(pk=int(request.POST['roomId']))
    emp=Employee.objects.get(id=int(request.session.get('userId',default=0)))

    emps=request.POST.getlist('emps[]')
    emps=list(set(emps))
    if(room.permissions>emp.permissions):
        return HttpResponseRedirect('/index/')
    roomBooking=RoomBooking()
    roomBooking.start=int(request.POST['startTime'])
    roomBooking.end=int(request.POST['endTime'])
    date=request.POST['date']
    date_time = datetime.datetime.strptime(date, '%Y-%m-%d')
    roomBooking.bookDate=date_time.date()
    if (checkTimeConflict(roomBooking.start,roomBooking.end,date_time,room,0) ==False):
        request.session['bookAnswer']=False
        return HttpResponseRedirect('/index/')
    request.session['bookAnswer'] = True
    roomBooking.topic=request.POST['topic']
    roomBooking.empCount=int(request.POST['meetingCount'])
    roomBooking.roomId=room
    roomBooking.empId=emp
    pswd=request.session.get('password')
    roomBooking.save()
    for i in emps:
        meetintemp=MeetingEmp()
        meetintemp.roomBook=roomBooking
        meetintemp.room=room
        meetintemp.emp=Employee.objects.get(pk=int(i))
        meetintemp.meetDate=roomBooking.bookDate
        meetintemp.save()
    return HttpResponseRedirect('/index/')

def mybook(request):
    context={}
    searchStart = request.POST.get("searchStart")
    searchEnd = request.POST.get("searchEnd")
    myRoombooks=None
    rooms = list(Room.objects.filter(state=True))
    if searchStart is not None:
        dateStart = datetime.datetime.strptime(searchStart, '%Y-%m-%d')
        if searchEnd is not None and searchEnd is not '':
            dateEnd=datetime.datetime.strptime(searchEnd, '%Y-%m-%d')
            myRoombooks = RoomBooking.objects.filter(empId=int(request.session.get('userId')),
                                                     bookDate__gte=dateStart,bookDate__lte=dateEnd).order_by('bookDate')
        else:
            myRoombooks=RoomBooking.objects.filter(empId=int(request.session.get('userId')),
                                                   bookDate__gte=dateStart).order_by('bookDate')
    else:
        today=datetime.datetime.strptime(datetime.date.today().strftime("%Y-%m-%d"), '%Y-%m-%d')
        myRoombooks=RoomBooking.objects.filter(empId=int(request.session.get('userId')),
                                               bookDate__gte=today).order_by('bookDate')
    answers=list()
    for roombook in myRoombooks:
        answer={}
        start=str(int((9+(roombook.start-1)/2)))+":"
        if((roombook.start-1)%2==0):
            start+="00"
        else:
            start+="30"
        end=str(int((9+(roombook.end+roombook.start-1)/2)))+":"
        if ((roombook.end+roombook.start-1)% 2 == 0):
            end += "00"
        else:
            end += "30"
        answer['start']=start
        answer['end']=end
        answer['roomBook']=roombook
        answers.append(answer)
    context['myRoombooks']=answers
    context['rooms']=rooms
    context['searchStart']=searchStart
    context['searchEnd']=searchEnd
    return render(request, 'mybook.html', context)


def getRoomBooking(request):
    context={}
    try:
        roomBookId=request.POST['roomBookId']
        roomBook = RoomBooking.objects.get(pk=roomBookId)
        context['success']=True
        context['topic']=roomBook.topic
        context['start']=roomBook.start
        context['end']=roomBook.end
        context['empCount']=roomBook.empCount
        context['roomId']=roomBook.roomId.id
        context['username']=roomBook.empId.name
        context['useremail']=roomBook.empId.mail
        context['pswd']=roomBook.empId.password
        context['data']=roomBook.bookDate.strftime('%Y-%m-%d')
    except ObjectDoesNotExist:
        print("Oops!  That was no valid number.  Try again   ")
        context['success']=False
        return JsonResponse(context, safe=False)
    return JsonResponse(context, safe=False)
def bookedit(request):
    roomBookId=int(request.POST['roomBookId'])
    roomBook=RoomBooking.objects.get(pk=roomBookId)
    roomBook.start=int(request.POST['start'])
    roomBook.end=int(request.POST['end'])#-roomBook.start+1
    date = request.POST['roomdate']
    roomBook.bookDate=datetime.datetime.strptime(date, '%Y-%m-%d')
    roomBook.empCount=int(request.POST['empCount'])
    roomBook.roomId=Room.objects.get(pk=int(request.POST['roomId']))

    if(checkTimeConflict(roomBook.start,roomBook.end,roomBook.bookDate,roomBook.roomId,roomBookId)):
        roomBook.save();
    else:
        request.session['message']="会议时间冲突"
    print(request)
    return HttpResponseRedirect('/mybook/')


def checkTimeConflict(start,end,dates,room,roomBookId):
    bookrooms = list(RoomBooking.objects.filter(roomId=room, bookDate=dates))
    end =start+end-1
    for booroom in bookrooms:
        if booroom.id != roomBookId:
            bookstart=booroom.start
            bookend=booroom.start+booroom.end-1
            if(start>=bookstart and start<=bookend):
                return False
            if(end>=bookstart and end<=bookend):
                return False
            if(start<=bookstart and end>=bookend):
                return False
    return True


def bookDetail(request):
    context={}
    roomBookId = request.POST['roomBookId']
    roombook = RoomBooking.objects.get(pk=roomBookId)
    context['roomBook']=roombook
    start = str(int((9 + roombook.start / 2))) + ":"
    if ((roombook.start - 1) % 2 == 0):
        start += "00"
    else:
        start += "30"
    end = str(int((9 + (roombook.end + roombook.start - 1) / 2))) + ":"
    if ((roombook.end + roombook.start - 1) % 2 == 0):
        end += "00"
    else:
        end += "30"
    context['start']=start
    context['end']=end
    emps=list(MeetingEmp.objects.filter(roomBook=roombook))
    context['emps']=emps
    return render(request, 'bookDetail.html', context)
def deleteMyRoomBooking(request):
    try:
        roomBookId=request.POST['roomBookId']
        roomBook=RoomBooking.objects.get(pk=roomBookId,empId=Employee.objects.get(pk=int(request.session.get('userId'))))
        roomBook.delete()
    except ObjectDoesNotExist:
        print("Oops!  That was no valid number.  Try again   ")
        return HttpResponseRedirect('/mybook/')
    return HttpResponseRedirect('/mybook/')

def meetingApproval(request):
    context = {}
    myRoombooks = RoomBooking.objects.all().order_by('bookDate')
    answers = list()
    for roombook in myRoombooks:
        answer = {}
        start = str(int((9 + roombook.start / 2))) + ":"
        if ((roombook.start - 1) % 2 == 0):
            start += "00"
        else:
            start += "30"
        end = str(int((9 + (roombook.end + roombook.start - 1) / 2))) + ":"
        if ((roombook.end + roombook.start - 1) % 2 == 0):
            end += "00"
        else:
            end += "30"
        answer['start'] = start
        answer['end'] = end
        answer['roomBook'] = roombook
        answers.append(answer)
    context['myRoombooks'] = answers

    return render(request, 'meetingApproval.html', context)
def passRoomBook(request):
    roomBook=RoomBooking.objects.get(pk=request.POST['roomBookId'])
    roomBook.state=int(request.POST['state'])
    roomBook.save()
    return HttpResponseRedirect('/meetingApproval/')

def myjoinMeeting(request):
    context = {}

    searchStart = request.POST.get("searchStart")
    searchEnd = request.POST.get("searchEnd")
    myRoombooks = None
    rooms = list(Room.objects.filter(state=True))
    if searchStart is not None:
        dateStart = datetime.datetime.strptime(searchStart, '%Y-%m-%d')
        if searchEnd is not None and searchEnd is not '':
            dateEnd = datetime.datetime.strptime(searchEnd, '%Y-%m-%d')
            myjoinMeetings = MeetingEmp.objects.filter(emp=int(request.session.get('userId')), meetDate__gte=dateStart,
                                                     meetDate__lte=dateEnd).order_by('meetDate')
        else:
            myjoinMeetings = MeetingEmp.objects.filter(emp=int(request.session.get('userId')),
                                                     meetDate__gte=dateStart).order_by('meetDate')
    else:
        today = datetime.datetime.strptime(datetime.date.today().strftime("%Y-%m-%d"), '%Y-%m-%d')
        myjoinMeetings = MeetingEmp.objects.filter(emp=Employee.objects.get(pk=int(request.session.get('userId'))),
                                                   meetDate__gte=today).order_by('meetDate')
    answers = list()
    for roombookemp in myjoinMeetings:
        answer = {}
        start = str(int((9 + (roombookemp.roomBook.start - 1) / 2))) + ":"
        if ((roombookemp.roomBook.start - 1) % 2 == 0):
            start += "00"
        else:
            start += "30"
        end = str(int((9 + (roombookemp.roomBook.end + roombookemp.roomBook.start - 1) / 2))) + ":"
        if ((roombookemp.roomBook.end + roombookemp.roomBook.start - 1) % 2 == 0):
            end += "00"
        else:
            end += "30"
        answer['start'] = start
        answer['end'] = end
        answer['roomBook'] = roombookemp.roomBook
        answers.append(answer)
    context['myRoombooks'] = answers
    context['rooms'] = rooms
    context['searchStart'] = searchStart
    context['searchEnd'] = searchEnd
    return render(request, 'myjoinmeeting.html', context)

